package app.qrcode.browser.hearttoheart.adapters

import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import app.qrcode.browser.hearttoheart.R

/**
 * Created by DomenCai on 2022/3/28.
 */
class StudentAdapter : RecyclerView.Adapter<StudentAdapter.StudentViewHolder>() {

    private val studentList: MutableList<Student> = mutableListOf()

    companion object {
        const val NORMAL_VIEW_TYPE = 0
        const val HEADER_VIEW_TYPE = 1
        const val INTRODUCTION = 2
    }

    @SuppressLint("NotifyDataSetChanged")
    fun updateList(newList: ArrayList<Student>) {
        studentList.clear()
        studentList.addAll(newList)
        notifyDataSetChanged()
    }

    inner class StudentViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val studentNameTV: TextView? = view.findViewById(R.id.stuName_TV)
        val studentHead: ImageView? = view.findViewById(R.id.student_head)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): StudentViewHolder {
        val viewHolder: StudentViewHolder
        when (viewType) {
            HEADER_VIEW_TYPE -> {
                viewHolder = StudentViewHolder(
                    LayoutInflater.from(parent.context)
                        .inflate(R.layout.head_item_class_control, parent, false)
                )
            }
            INTRODUCTION -> {
                viewHolder = StudentViewHolder(
                    LayoutInflater.from(parent.context)
                        .inflate(R.layout.item_introduction, parent, false)
                )
            }
            else -> {
                viewHolder = StudentViewHolder(
                    LayoutInflater.from(parent.context)
                        .inflate(R.layout.item_student, parent, false)
                )
            }
        }
        return viewHolder
    }

    override fun getItemViewType(position: Int): Int {
        return if (position == 0) HEADER_VIEW_TYPE else if (position == 1) INTRODUCTION else NORMAL_VIEW_TYPE
    }

    override fun onBindViewHolder(holder: StudentViewHolder, position: Int) {
        val student = studentList[position]
        if (position == 0 || position == 1) {
            return
        } else {
            student.photo?.let { holder.studentHead?.setImageResource(it) }
            holder.studentNameTV?.text = student.stuName
        }
    }

    override fun getItemCount(): Int = studentList.size

}